﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using EntityFrameworks.Entity.Core.Specification;

namespace Common.Background.BLL
{
    /// <summary>
    /// 用户列表规约
    /// 对参数进行有效性判断，赋默认值等
    /// </summary>
    public class UserSpecification : Specification<WebManageUsers>
    {
        #region Fields
        private DateTime? _fromDate;
        private DateTime? _toDate;
        private string _userName;
        private string _deptName;
        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor for OrderDateSpecification
        /// </summary>
        /// <param name="fromDate">From date</param>
        /// <param name="toDate">To date</param>
        public UserSpecification(DateTime? fromDate, DateTime? toDate, string userName, string deptName)
        {
            _fromDate = fromDate;
            _toDate = toDate;
            _userName = userName;
            _deptName = deptName;
        }

        #endregion

        #region Specification Overrides
        public override Expression<Func<WebManageUsers, bool>> SatisfiedBy()
        {
            Specification<WebManageUsers> spec = new TrueSpecification<WebManageUsers>();
            if (_fromDate.HasValue)
                spec &= new DirectSpecification<WebManageUsers>(o => o.CreateDate > _fromDate);
            
            if (_toDate.HasValue)
                spec &= new DirectSpecification<WebManageUsers>(o => o.CreateDate < _toDate);

            if (!string.IsNullOrWhiteSpace(_userName))
                spec &= new DirectSpecification<WebManageUsers>(o => o.LoginName.Contains(_userName.Trim()));

            if (!string.IsNullOrWhiteSpace(_deptName))
                spec &= new DirectSpecification<WebManageUsers>(o => o.WebDepartments.DepartmentName.Contains(_deptName.Trim()));
            return spec.SatisfiedBy();
        }

        #endregion
    }
}